package com.geoai.uimap.core.osmdroid

import com.geoai.uimap.api.IGEOMap
import com.geoai.uimap.api.GEOMapCircle
import com.geoai.uimap.geo.Point
import com.geoai.uimap.geo.SimpleProjection
import com.geoai.uimap.utils.MathUtils
import com.geoai.uimap.utils.getOsmMapView
import org.osmdroid.util.GeoPoint
import org.osmdroid.views.overlay.Polygon

class OsmMapCircle(private val map: IGEOMap) : GEOMapCircle() {
    private var mCircle: Polygon? = null
    override fun show(): GEOMapCircle {
        val mapView = map.getOsmMapView() ?: return this
        centerPoint?.let {
            val simpleProjection = SimpleProjection(it) //基点
            val preTurnFirstPoint = simpleProjection.GeoPoint2Point(centerPoint)
            val circleOnAftTurn: MathUtils.Circle = MathUtils.Circle()
            circleOnAftTurn.center.x = preTurnFirstPoint.x
            circleOnAftTurn.center.y = preTurnFirstPoint.y
            circleOnAftTurn.radius = mRadius
            val allPoints = mutableListOf<GeoPoint>()
            var startAngle = 0.0
            while (startAngle <= 360.0) {
                val p = MathUtils.getPointOnCircle(circleOnAftTurn, Math.toRadians(startAngle))
                val midPoint = simpleProjection.Point2GeoPoint(Point(p.x, p.y))
                allPoints.add(GeoPoint(midPoint.latitude, midPoint.longitude))
                startAngle += 3.0
            }
            mCircle = Polygon(mapView)
            mCircle?.points = allPoints
            mCircle?.outlinePaint?.color = mStrokeColor
            mCircle?.outlinePaint?.strokeWidth = mStrokeWidth
            mCircle?.fillPaint?.color = mColor
            mapView.overlayManager.add(mCircle)
            mapView.invalidate()
        }
        return this
    }

    override fun destroy() {
        map.getOsmMapView()?.let {
            it.overlayManager.remove(mCircle)
            it.invalidate()
        }
    }
}